package com.jjc.android.fragment

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.text.InputType
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.IdRes
import com.allen.library.SuperButton
import com.github.gzuliyujiang.wheelpicker.DatePicker
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.google.gson.reflect.TypeToken
import com.hjq.toast.ToastUtils
import com.jjc.android.Constants
import com.jjc.android.R
import com.jjc.android.UserManager
import com.jjc.android.activity.AddTestedPersonActivity
import com.jjc.android.activity.DetectionActivity
import com.jjc.android.activity.SamplingActivity
import com.jjc.android.base.BaseLazyLoadFragment
import com.jjc.android.dialog.AttachListDialog
import com.jjc.android.dialog.BottomWheelDialog
import com.jjc.android.entity.*
import com.jjc.android.net.SimpleHttpCallback
import com.jjc.android.util.*
import com.jjc.android.util.Common.parseEmpty
import com.jjc.android.util.Common.parseInt
import com.jjc.android.view.CommonKt.genderParse
import com.jjc.android.view.formatTwo
import com.jjc.android.view.layout.*
import com.jjc.android.view.onClick
import com.jjc.android.view.textChange
import com.lzy.okgo.OkGo
import com.xw.repo.XEditText
import org.greenrobot.eventbus.EventBus
import kotlin.properties.Delegates

class FillProductInfoFragment : BaseLazyLoadFragment(),OnDetectionPageListener{

    companion object{

        fun newInstance(testerId:String?,deviceSn:String):FillProductInfoFragment{
            val fragment = FillProductInfoFragment()
            fragment.setupArguments(Bundle().apply {
                putString("testerId",testerId)
                putString("deviceSn",deviceSn)
            })
            fragment.setInflateLazy(true)
            return fragment
        }
    }

    override fun getLayoutId(): Int = R.layout.fragment_fill_product_info

    private val okBtn: SuperButton by lazy { findViewById<SuperButton>(R.id.okBtn) }
    private val weightEt: XEditText by lazy { findViewById<XEditText>(R.id.weightEt) }
    private val tallEt: XEditText by lazy { findViewById<XEditText>(R.id.tallEt) }
    private val chooseBirthDayBtn: TextView by lazy { findViewById<TextView>(R.id.chooseBirthDayBtn) }
    private val chooseGenderBtn: TextView by lazy { findViewById<TextView>(R.id.chooseGenderBtn) }
    private val nameEt: XEditText by lazy { findViewById(R.id.nameEt) }
    private val productNameTxt: TextView by lazy { findViewById<TextView>(R.id.productNameTxt) }
    private val chooseTesterBtn:View by lazy { findViewById(R.id.chooseTesterBtn) }
    private val extroFillLayout:LinearLayout by lazy { findViewById(R.id.extroFillLayout) }
    private var scanDeviceDto:ScanCardDto? = null
    private var testerId:String? = null
    private var deviceSn:String = ""



    override fun initView(view: View) {

        tallEt.filters = arrayOf(InputFilterMinMax(0f,250f))
        weightEt.filters = arrayOf(InputFilterMinMax(0f,400f))
        chooseTesterBtn.onClick {
            AttachListDialog<TestedPersonDto>(chooseTesterBtn)
                .contentList(testedPersonList)
                .onItemClick { _, value ->
                    if(value == addTesterMode){
                        AddTestedPersonActivity.start(requireActivity()){
                            fetchTesters(it)
                        }
                    }else{
                        currentTester = value
                    }
                }
                .build()
                .show()
        }
        okBtn.onClick {
            submit()
        }
        chooseGenderBtn.onClick {
            genderDialog.show()
        }
        chooseBirthDayBtn.onClick {
            birthdayPicker.show()
        }
        val action:(String)->Unit = {
            checkBtnEnable()
        }
        nameEt.textChange(action = action)
        weightEt.textChange(action = action)
        tallEt.textChange(action = action)
        fetchPageInfo()
    }

    override fun onCurrentStepInvoke() {
        if(ismIsFirstVisible()) return
        extroFillLayout.removeAllViews()
        fillExtraList.clear()
        chooseGenderBtn.text = ""
        chooseBirthDayBtn.text = ""
        tallEt.setText("")
        weightEt.setText("")
        fetchPageInfo()
    }

    private fun checkBtnEnable(){
        okBtn.isEnabled = true
    }

    private fun submit(){
        if(nameEt.textEx.isNullOrEmpty()){
            ToastUtils.show(getString(R.string.input_name_txt))
            return
        }
        if(chooseGenderBtn.text.isNullOrEmpty()){
            ToastUtils.show(getString(R.string.choose_gender))
            return
        }
        if(chooseBirthDayBtn.text.isNullOrEmpty()){
            ToastUtils.show(getString(R.string.choose_date_txt))
            return
        }
        if(tallEt.textEx.isNullOrEmpty()){
            ToastUtils.show(getString(R.string.input_tall_txt))
            return
        }
        if(weightEt.textEx.isNullOrEmpty()){
            ToastUtils.show(getString(R.string.input_weight_fx_txt))
            return
        }
        if(!fillExtraList.isNullOrEmpty()){
            fillExtraList.forEach { target->
                if(target.second.visibility == View.VISIBLE &&target.second.text.isNullOrEmpty()){
                    ToastUtils.show(target.first.prompt)
                    return
                }
            }
        }
        showLoadingDialog()
        modifyTester{testerId->
            if(!testerId.isNullOrEmpty()){
                val detectionInfo = DetectionInfo().apply {
                    scanDeviceDto?.lcq6twxkuyytwpkc?.let {
                        if(!it.isNullOrEmpty()){
                            val info = it[0]
                            minorTermId = info.id

                        }
                    }
                    minorTermName = scanDeviceDto?.jsonMember4arvpt0ckfechc6h
                    minorTermEnglishName = scanDeviceDto?.d5zyxqmhtbzruvz6
                    detectionUserId = testerId
                    detectionUserName = nameEt.textEx
                    gender = chooseGenderBtn.text.toString().genderParse(true)
                    birthday = chooseBirthDayBtn.text.toString()
                    age = Common.getAge(chooseBirthDayBtn.text.toString()).toString()
                    height = tallEt.textEx.parseInt()
                    weight = weightEt.textEx.parseInt()
                    exInputs = ArrayList<KeyValuePair>().also {
                        it.addAll(fillExtraList.filter { it.second.visibility == View.VISIBLE }.map { pair->
                            KeyValuePair(pair.first.fieldName,pair.second.text.toString())
                        })
                    }
                    deviceId = deviceSn
                    stickerId = scanDeviceDto?.tkynuu9ecdit0llv
                    waitTime = scanDeviceDto?.danmoe2hn6ie3yqu.parseInt()
                    measLowEnd = scanDeviceDto?.v6qpfu0mxss3cw1t.parseInt()
                    measHighEnd = scanDeviceDto?.wn3d1qkftirpidef.parseInt()
                    measUnit = scanDeviceDto?.n7cplrqzmakiyazi
                    volumeUnit = scanDeviceDto?.jsonMember3ntlcnyxsmlzs1w0
                }
                hideLoadingDialog()
                closeKeyboard()
                (activity as? DetectionActivity)?.let { activity->
                    activity.saveDetectionInfo(detectionInfo)
                    activity.nextStep()
                }
            }else{
                hideLoadingDialog()
            }
        }
    }

    private fun closeKeyboard() {
        val m = context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val isOpen = m.isActive
        if (isOpen) {
            m.hideSoftInputFromWindow((context as Activity).currentFocus?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

    private fun modifyTester(action:(String?)->Unit){
        if(currentTester==null){
            OkGo.post<LzyResponse<IdValuePair>>(Constants.addFormRow)
                .paramEx(mutableMapOf(
                    "formheaduuid" to "83ed64e98f6c4edbaf7b388d7691e57b",
                    "fields" to mapOf<String,Any?>("61xugqtzoyid5pw2" to UserManager.userId(),
                        "8pa55qzbspju5tzn" to nameEt.textEx,
                        "cu8thtdjxhfbxpjx" to tallEt.textEx,
                        "kpurkwtmvsd9lqui" to chooseGenderBtn.text.toString().genderParse(true),
                        "orldw605kccdju8z" to chooseBirthDayBtn.text.toString(),
                        "yzqfbls6zzqh9tyl" to weightEt.textEx)
                ),true)
                .tag(this@FillProductInfoFragment)
                .execute(object : SimpleHttpCallback<LzyResponse<IdValuePair>>(){
                    override fun onCallSuccess(response: LzyResponse<IdValuePair>) {
                        EventBus.getDefault().post(ChangeTesterEvent())
                        action.invoke(response.data?.id)
                    }

                    override fun onCallError(error: String?) {
                        super.onCallError(error)
                        action.invoke(null)
                    }
                })
        }else{
            OkGo.post<LzyResponse<Any>>(Constants.editFormRowById)
                .paramEx(mutableMapOf(
                    "formheaduuid" to "83ed64e98f6c4edbaf7b388d7691e57b",
                    "rowid" to currentTester?.id,
                    "fields" to mapOf<String,Any?>(
                        "8pa55qzbspju5tzn" to nameEt.textEx,
                        "cu8thtdjxhfbxpjx" to tallEt.textEx,
                        "kpurkwtmvsd9lqui" to chooseGenderBtn.text.toString().genderParse(true),
                        "orldw605kccdju8z" to chooseBirthDayBtn.text.toString(),
                        "yzqfbls6zzqh9tyl" to weightEt.textEx)
                ),true)
                .tag(this@FillProductInfoFragment)
                .execute(object : SimpleHttpCallback<LzyResponse<Any>>(){
                    override fun onCallSuccess(response: LzyResponse<Any>) {
                        EventBus.getDefault().post(ChangeTesterEvent())
                        action.invoke(currentTester?.id)
                    }

                    override fun onCallError(error: String?) {
                        super.onCallError(error)
                        action.invoke(null)
                    }

                })
        }
    }
    private val fillExtraList:ArrayList<Pair<DetectionFillInfo,TextView>> = ArrayList()
    private fun createFillLayout(data:List<DetectionFillInfo>?){
        extroFillLayout.removeAllViews()
        fillExtraList.clear()
        if(data.isNullOrEmpty()) return
        data.forEach {info->
            extroFillLayout.LinearLayout {
                layout_width = match_parent
                layout_height = 50
                margin_top = 15
                padding_start_end = 15
                background_res = R.drawable.shape_et_bg
                TextView {
                    layout_width = wrap_content
                    layout_height = wrap_content
                    layout_gravity = Gravity.CENTER_VERTICAL
                    textStyle = bold
                    textSize = 16f
                    textColorRes = R.color.c_333333
                    text = info.fieldTxt
                }
                if(info.fieldType == Constants.FieldType.SELECT||info.fieldType == Constants.FieldType.DATE){
                    TextView {
                        layout_width = 0
                        layout_height = match_parent
                        weight = 1f
                        gravity = gravity_right or gravity_center_vertical
                        drawable_padding = 15
                        drawable_end = R.mipmap.tuya_nav_icon_down
                        hint = info.prompt
                        textColorRes = R.color.c_333333
                        setHintTextColor(context.getColor(R.color.c_999999))
                        textSize = 16f
                        margin_start = 15
                        setLines(1)
                        ellipsize = TextUtils.TruncateAt.END
                        onClick {
                            clickSelect(info,this)
                        }
                        fillExtraList.add(Pair(info,this))
                    }
                }else{
                    XEditText{
                        layout_width = 0
                        layout_height = match_parent
                        weight = 1f
                        gravity = gravity_right or gravity_center_vertical
                        drawable_padding = 15
                        drawable_end = R.mipmap.tuya_nav_icon_down
                        hint = info.prompt
                        textColorRes = R.color.c_333333
                        setHintTextColor(context.getColor(R.color.c_999999))
                        textSize = 16f
                        margin_start = 15
                        background_res = 0
                        inputType = if(info.fieldType == Constants.FieldType.NUMBER) (InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL or InputType.TYPE_NUMBER_FLAG_SIGNED) else InputType.TYPE_CLASS_TEXT
                        textChange {
                            checkBtnEnable()
                        }
                        fillExtraList.add(Pair(info,this))
                    }
                }
                if(info.fieldName=="sampleVolume"){
                    visibility = View.GONE
                }
            }
        }
    }

    private fun clickSelect(info:DetectionFillInfo,textView:TextView){
        if(info.fieldType == Constants.FieldType.DATE){
            val picker = DatePicker(requireActivity())
            picker.wheelLayout.setRange(DateEntity.yearOnFuture(-100), DateEntity.today())
            picker.wheelLayout.setDefaultValue(
                if(textView.text.isNullOrEmpty()){
                    DateEntity.today()
                }else{
                    try {
                        DateEntity.target(Common.yymmdd2.parse(textView.text.toString()))
                    }catch (e:Exception){
                        DateEntity.today()
                    }
                }
            )
            picker.setOnDatePickedListener { year, month, day ->
                textView.text = String.format("%d-%s-%s", year, month.formatTwo(), day.formatTwo())
                checkBtnEnable()
            }
            picker.show()
            return
        }
        if(info.options.isNullOrEmpty()) return
        BottomWheelDialog<String>(requireActivity())
            .title(info.prompt)
            .contentList(info.options)
            .onItemClick { _, value ->
                clickSelectItem(textView,value)
            }
            .build()
            .show()
    }

    private fun clickSelectItem(textView:TextView,value:String){
        textView.text = value
        fillExtraList.find {
            it.first.fieldName=="sampleVolume"
        }?.let { pair->
            if(value.contains("24")){
                (pair.second.parent as? View)?.visibility = View.VISIBLE
                pair.second.visibility = View.VISIBLE
            }else{
                (pair.second.parent as? View)?.visibility = View.GONE
                pair.second.visibility = View.GONE
            }
        }
        checkBtnEnable()
    }

    private val genderDialog by lazy {
        BottomWheelDialog<KeyValuePair>(requireActivity())
            .title(getString(R.string.choose_gender_txt))
            .contentList(listOf(
                KeyValuePair(Constants.Gender_Woman, getString(R.string.woman_txt)),
                KeyValuePair(Constants.Gender_Man, getString(R.string.man_txt))
            ))
            .onItemClick { position, value ->
                chooseGenderBtn.text = value.value
                checkBtnEnable()
            }
            .build()
    }

    private val birthdayPicker: DatePicker by lazy {
        val picker = DatePicker(requireActivity())
        picker.wheelLayout.setRange(DateEntity.yearOnFuture(-100), DateEntity.today())
        picker.setOnDatePickedListener { year, month, day ->
            chooseBirthDayBtn.text = String.format("%d-%s-%s", year, month.formatTwo(), day.formatTwo())
            checkBtnEnable()
        }
        picker
    }



    override fun fetchPageInfo() {
        scanDeviceDto?:return
        fetchTesters()
        OkGo.post<LzyResponse<PageInfo<DetectionFillPageDto>>>(Constants.getFormList)
            .paramEx(mutableMapOf("page" to 1,"pagesize" to 1,"needpage" to 1,"formheaduuid" to "ded7b290da4641309118a69a18fc89b8","filters" to listOf<KeyValuePair>(
                KeyValuePair("tfilhnr91gkmekdd",scanDeviceDto?.lcq6twxkuyytwpkc.let { if(it.isNullOrEmpty()) "" else it[0].id}),
                KeyValuePair("yllmwtdxzftugo1h",
                    MultiLanguageUtil.getInstance().getValue("7599b8c0-e0d2-45d2-aaee-ba9de5a349be","86249b3a-0a54-4602-9d49-d8deafc850a6"))
            )),true)
            .tag(this)
            .execute(object : SimpleHttpCallback<LzyResponse<PageInfo<DetectionFillPageDto>>>(){
                override fun onCallSuccess(response: LzyResponse<PageInfo<DetectionFillPageDto>>) {
                    productNameTxt.text = scanDeviceDto?.jsonMember4arvpt0ckfechc6h.parseEmpty()
                    createFillLayout(response.data?.data?.let {
                        if(it.isNullOrEmpty()){
                            null
                        }else{
                            it.first()
                        }
                    }?.also {
                        if(!it.tfilhnr91gkmekdd.isNullOrEmpty()){
                            productNameTxt.text = it.tfilhnr91gkmekdd[0].value
                        }
                    }?.e5tlqxpbrortyd6x?.let {
                        try {
                            Convert.fromJson<List<DetectionFillInfo>>(it,object : TypeToken<List<DetectionFillInfo>>(){}.type)
                        }catch (e:Exception){
                            null
                        }
                    })
                    handleDefault()
                }
            })
    }

    private fun handleDefault(){
        if(!fillExtraList.isNullOrEmpty()){
            fillExtraList.forEachIndexed { index, pair ->
                if(pair.first.fieldType == Constants.FieldType.SELECT){
                    pair.first.options.forEachIndexed { childIndex, s ->
                        if(!s.isNullOrEmpty()&&s.contains("24")){
                            clickSelectItem(pair.second,s)
                            return
                        }
                    }
                }
            }
        }
    }

    private val testedPersonList = ArrayList<TestedPersonDto>()
    private var currentTester:TestedPersonDto? by Delegates.observable(null){ _, old, new->
        if(new==null){
            nameEt.setText("")
        }else{
            nameEt.setText(new.provideText())
            chooseGenderBtn.text = new.kpurkwtmvsd9lqui.genderParse(false)
            chooseBirthDayBtn.text = new.orldw605kccdju8z.let { if(it.isNullOrEmpty()) "" else if(it.length>10) it.substring(0,10) else it }
            tallEt.setText(new.cu8thtdjxhfbxpjx)
            weightEt.setText(new.yzqfbls6zzqh9tyl)
        }
    }
    private val addTesterMode: TestedPersonDto by lazy {
        TestedPersonDto().apply {
            jsonMember8pa55qzbspju5tzn = getString(R.string.newly_add_txt)
            id = "-1"
        }
    }

    private fun fetchTesters(targetId:String? = null){
        OkGo.post<LzyResponse<PageInfo<TestedPersonDto>>>(Constants.getFormList)
            .paramEx(mutableMapOf("page" to 1,"pagesize" to 100,"needpage" to 0,"formheaduuid" to "83ed64e98f6c4edbaf7b388d7691e57b","filters" to listOf<KeyValuePair>(
                KeyValuePair("61xugqtzoyid5pw2",UserManager.userId())
            )),true)
            .tag(this)
            .execute(object : SimpleHttpCallback<LzyResponse<PageInfo<TestedPersonDto>>>(false){
                override fun onCallSuccess(response: LzyResponse<PageInfo<TestedPersonDto>>) {
                    response.data?.data?.let {
                        testedPersonList.clear()
                        testedPersonList.addAll(it)
                        testedPersonList.add(addTesterMode)
                    }
                    val testerId = if(targetId.isNullOrEmpty()) testerId else targetId
                    if(!testedPersonList.isNullOrEmpty()&&testedPersonList.size>1){
                        currentTester = if(testerId.isNullOrEmpty()){
                            testedPersonList[0]
                        }else{
                            testedPersonList.find { it.id == testerId }
                        }
                        chooseTesterBtn.visibility = View.VISIBLE
                    }else{
                        chooseTesterBtn.visibility = View.GONE
                    }
                }

                override fun onCallError(error: String?) {
                    super.onCallError(error)
                }
            })
    }

    override fun onFragmentResume() {
        super.onFragmentResume()
        scanDeviceDto = (activity as? DetectionActivity)?.getScanCardInfo()
    }

    override fun setupArguments(args: Bundle?) {
        testerId = args?.getString("testerId")
        deviceSn = args?.getString("deviceSn")?:""
    }


    private fun <T : View?> findViewById(@IdRes id: Int): T {
        return rootView!!.findViewById<T>(id)
    }

}